package com.usian.controller;


import com.usian.game.Game;
import com.usian.message.Message;
import com.usian.service.GameService;
import com.usian.vo.Result;
import com.usian.vote.Vote;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/app/game")
public class GameController {
    @Autowired
    private GameService gameService;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/startGame/{roomid}")
    public String startGame(@PathVariable Integer roomid){
        gameService.startGame(roomid);
        return "success";
    }
    @RequestMapping("/getGameUser/{roomid}")
    public List<Game> getGameUser(@PathVariable Integer roomid){
        return gameService.getGameUser(roomid);
    }
    @RequestMapping("/sendMessage")
    public String sendMessage(@RequestBody Message message){
        gameService.sendMessage(message);
        return "success";
    }
    @RequestMapping("/getGameMessage/{roomid}")
    public List<Message> getGameMessage(@PathVariable Integer roomid){
        return gameService.getGameMessage(roomid);
    }
    @RequestMapping("/getGameWerewolfMessage/{roomid}")
    public List<Message> getGameWerewolfMessage(@PathVariable Integer roomid){
        return gameService.getGameWerewolfMessage(roomid);
    }

    /**
     * 接口：根据传过来的房间id来查询女巫这个角色是否有毒
     */
    @RequestMapping("/getPoison/{roomid}")
    public Result getPoison(@PathVariable Integer roomid){
        Integer poison = gameService.getPosion(roomid);
        if (poison == null){
            return null;
        }
        return Result.success();
    }

    @RequestMapping("/sibylselect/{roomid}")
   public List<Game> sibylselect(@PathVariable Integer roomid){
        List<Game> games = redisTemplate.opsForList().range(roomid+"death", 0, -1);
        if (games != null){
            return games;
        }
        return null;
    }

    /**
     * 接口：根据传过来的房间id，用户id，被杀人的id，进行判断，首先判断狼人数量如果为2，
     * 那么就判断被杀的人是否是女巫，如果是，那么就判断女巫是否使用了毒药，如果使用了，
     * 那么就判断是否使用了解药，如果没有使用就添加到，假死字段，如果使用了那就直接死亡
     * 如果狼人数量大于2，那么就判断被杀的人是否是女巫，如果是，那么就判断女巫是否使用了毒药，
     * 如果使用了，那么就判断是否使用了解药，如果没有使用就添加到，假死字段，如果使用了那就直接死亡
     * 如果女巫没有使用的话那就直接死亡
     * 狼人杀完人之后，把对应的技能字段在redis里面的skill改为0，回合结束后再把skill改为1
     */
    @RequestMapping("/killUser/{roomid}/{userId}/{killUserId}")
    public Result killUser(@PathVariable Integer roomid,@PathVariable Integer userId,@PathVariable Integer killUserId){
        gameService.killUser(roomid,userId,killUserId);
        return Result.success();
    }


    @RequestMapping("/showindex/{userid}")
    public String showindex(@PathVariable Integer userid){
        return gameService.showindex(userid);
    }

    @RequestMapping("/rescue/{roomid}")
    public void rescue(@PathVariable Integer roomid){
         redisTemplate.delete(roomid + "death");
    }
    @RequestMapping("/poisonround/{roomid}/{round}")
    public void poisonround(@PathVariable Integer roomid, @PathVariable Integer round) {
        // 从 Redis 获取当前轮次
        Object indexObj = redisTemplate.opsForValue().get(roomid + "round");
        if (round == 2){
            gameService.poisonround(roomid, round);
        }
        // 检查 indexObj 是否为 null
        if (indexObj == null) {
            // 如果 indexObj 为 null，直接设置新的轮次
            redisTemplate.opsForValue().set(roomid + "round", round, 2, TimeUnit.MINUTES);
            return;
        }

        // 将 indexObj 转换为 Integer
        Integer currentIndex = (Integer) indexObj;

        // 比较当前轮次和传入的轮次
        if (currentIndex.equals(round)) {
            return;
        }
        // 更新轮次
        redisTemplate.opsForValue().set(roomid + "round", round, 2, TimeUnit.MINUTES);
    }
    @RequestMapping("/poison/{roodid}")
    public Integer poison(@PathVariable Integer roodid){
        // 获取并转换为 String 类型
        Object indexObj = redisTemplate.opsForValue().get(roodid + "round");
        if (indexObj != null) {
            Integer index;
            if (indexObj instanceof String) {
                // 如果是字符串，则解析为整数
                String indexStr = (String) indexObj;
                try {
                    index = Integer.parseInt(indexStr);
                } catch (NumberFormatException e) {
                    // 处理解析失败的情况
                    return -1; // 或者抛出异常
                }
            } else if (indexObj instanceof Integer) {
                // 如果已经是整数，则直接使用
                index = (Integer) indexObj;
            } else {
                // 处理其他类型的情况
                return -1; // 或者抛出异常
            }

            index++; // 澧炲姞 1

            // 鍒犻櫎鏃х殑閿�煎
            redisTemplate.delete(roodid + "round");
            // 璁剧疆鏂扮殑閿�煎
            redisTemplate.opsForValue().set(roodid + "round", index, 2, TimeUnit.MINUTES);
            return index;
        } else {
            // 如果没有找到对应的键值对
            return -1; // 或者抛出异常
        }
    }
    @RequestMapping("/poisonKill/{roomid}/{index}")
    public void poisonKill(@PathVariable Integer roomid,@PathVariable Integer index){
         gameService.poisonKill(roomid,index);
    }
    @RequestMapping("/jump/{roomid}/{userid}")
    public void jump(@PathVariable Integer roomid,@PathVariable Integer userid){
         gameService.jump(roomid,userid);
    }
    @RequestMapping("/getjump/{roomid}/{userid}")
    public Result getjump(@PathVariable Integer roomid,@PathVariable Integer userid){
        Object valueObj = redisTemplate.opsForValue().get(roomid + "jump" + userid);
        if (valueObj != null){
            return Result.success();
        }else {
            return null;
        }
    }
    @RequestMapping ("/vote/{roomId}/{indexUser}/{myindex}")
    public void castVote(@PathVariable Integer roomId, @PathVariable int indexUser, @PathVariable int myindex) {
        gameService.castVote(roomId, indexUser, myindex);
    }
    @RequestMapping("/VoteSelect/{roomid}")
    public Integer VoteSelect(@PathVariable Integer roomid){
        return gameService.VoteSelect(roomid);
    }
    @RequestMapping("/delateWhite/{roomid}")
    public void delateWhite(@PathVariable Integer roomid){
        List<Game> games = redisTemplate.opsForList().range(roomid+"death", 0, -1);
        for (Game game : games) {
            gameService.delateWhite(roomid,game.getId());
        }
        redisTemplate.delete(roomid + "KillUserId");
    }
    @RequestMapping("/WhiteDay/{roomid}/{daynum}")
    public void WhiteDay(@PathVariable Integer roomid,@PathVariable Integer daynum){
        Message message = new Message();
        message.setRoomId(roomid);
        message.setSendName("");
        message.setMessage("--------------第"+daynum+"天--------------");
        redisTemplate.opsForList().rightPush(roomid + "gamemessage", message);
        redisTemplate.expire(roomid + "gamemessage", 50, TimeUnit.MINUTES);
    }
    @RequestMapping("/black/deal/{roomid}")
    public void deal(@PathVariable Integer roomid){
        redisTemplate.delete(roomid+"death");
    }
    @RequestMapping("/hunterselect/{roomid}")
    public Boolean hunterselect(@PathVariable Integer roomid){
        Boolean hunter = (Boolean) redisTemplate.opsForValue().get(roomid+"hunter");
        return hunter;
    }
    @RequestMapping("/hunterstatus/{roomid}/{status}")
    public void hunterstatus(@PathVariable Integer roomid,@PathVariable String status){
        if (status.equals("true")){
            redisTemplate.opsForValue().set(roomid+"hunter",true,1, TimeUnit.MINUTES);
        }else {
            redisTemplate.opsForValue().set(roomid+"hunter",false,1, TimeUnit.MINUTES);
        }
    }
    @RequestMapping("/hunterkill/{roomid}/{index}")
    public void hunterkill(@PathVariable Integer roomid,@PathVariable Integer index){
         gameService.hunterkill(roomid,index);
    }
    @RequestMapping("/hunterKill/{roomid}")
    public Integer hunterKill(@PathVariable Integer roomid){
        return gameService.hunterKill(roomid);
    }
    @RequestMapping("/BlackDeal/{roomid}/{daynum}")
    public void BlackDeal(@PathVariable Integer roomid,@PathVariable Integer daynum){
        gameService.BlackDeal(roomid,daynum);
    }

    @RequestMapping("/goodendwin/{userid}")
    public void goodend(@PathVariable("userid") Integer userid){
        gameService.goodendwin(userid);
    }
    @RequestMapping("/badendwin/{userid}")
    public void badend(@PathVariable("userid") Integer userid){
        gameService.badendwin(userid);
    }
    @RequestMapping("/endfail/{userid}")
    public void endfail(@PathVariable("userid") Integer userId){
        gameService.endfail(userId);
    }
    @RequestMapping("/quitGame/{roomid}/{userid}")
    public void quitGame(@PathVariable Integer roomid,@PathVariable Integer userid){
        gameService.quitGame(roomid,userid);
    }
    @RequestMapping("/voteselect/{roomid}/{index}/{userid}")
    public void voteselect(@PathVariable Integer roomid,@PathVariable Integer index, @PathVariable Integer userid){
        gameService.voteselect(roomid,index,userid);
    }
    @RequestMapping("/NotVote/{roomid}/{userid}")
    public void voteselect(@PathVariable Integer roomid,@PathVariable Integer userid){
        redisTemplate.opsForList().rightPush(roomid+"NotVote",userid);
        redisTemplate.expire(roomid + "NotVote", 2, TimeUnit.MINUTES);
    }
    @RequestMapping("/VoteLook/{roomid}")
    public List<Vote> VoteLook(@PathVariable Integer roomid){
        return gameService.VoteLook(roomid);
    }
    @RequestMapping("/VoteJump/{roomid}")
    public Integer VoteJump(@PathVariable Integer roomid){
        return gameService.VoteJump(roomid);
    }
}
